package org.summerframework.component.security.core.handle;

import org.summerframework.component.security.LoginData;
import org.summerframework.component.security.annotion.LoginRequired;
import org.summerframework.component.security.core.RequestParamHandle;

import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Arrays;
import java.util.Map;

/**
 * @author 石超
 * @version v1.0.0
 */
public class UserIdRequestParamHandle implements RequestParamHandle<LoginRequired> {
    @Override
    public Class<LoginRequired> getAnnotation() {
        return LoginRequired.class;
    }

    @Override
    public void doRequest(LoginRequired loginRequired, HttpServletRequestWrapper request, LoginData<?> loginData) {
        final Map<String, String[]> parameter = request.getParameterMap();
        if (loginRequired.userIdParamNames().length > 0) {
            Arrays.asList(loginRequired.userIdParamNames()).forEach(userId -> {
                if (loginRequired.coerce()) {
                    parameter.put(userId, new String[]{loginData.getUserId().toString()});
                } else {
                    parameter.computeIfAbsent(userId, k -> new String[]{loginData.getUserId().toString()});
                }
            });
        }

        if (loginRequired.userIdParamNames().length > 0) {
            Arrays.asList(loginRequired.usernameParamNames()).forEach(username -> {
                if (loginRequired.coerce()) {
                    parameter.put(username, new String[]{loginData.getUserName()});
                } else {
                    parameter.computeIfAbsent(username, k -> new String[]{loginData.getUserName()});
                }
            });
        }
    }
}
